package handlers

import (
	"github.com/bitly/go-simplejson"
	"time"
	"generalhandler/conf"
)

type SubdomainFilterHanlder struct {

}

func (sfh *SubdomainFilterHanlder) Handle(bytesMsg []byte, log Logger, pub Publisher) error {
	start := time.Now().Unix()
	msg, err := simplejson.NewJson(bytesMsg)
	if nil != err {
		log.Warn("failed to NewJson %s, cuz %s", string(bytesMsg), err.Error())
		return nil
	}
	strDomain, err := msg.Get("domain").String()
	if nil != err {
		log.Warn("found no domain in %s", string(bytesMsg))
		return nil
	}
	strTkId, err := msg.Get("tkid").String()
	if nil != err {
		log.Warn("found no tkid in %s", string(bytesMsg))
		return nil
	}
	subDomains, ok := msg.CheckGet("subdomains")
	if !ok {
		log.Warn("found no subdomains in %s", string(bytesMsg))
		return nil
	}

	new := simplejson.New()
	new.Set("domain", strDomain)
	new.Set("tkid", strTkId)
	new.Set("start", start)
	var iflist []interface{}
	list, err := subDomains.Array()
	if nil != err {
		// one result
		item, err := subDomains.Map()
		if nil != err {
			log.Error("error %s in %v", err.Error(), subDomains)
			return nil
		}
		iflist = append(iflist, item)
	} else {
		// results
		iflist = append(iflist, list...)
	}
	tmp := simplejson.New()
	tmp.Set("subdomains", iflist)
	newSubDomains := tmp.Get("subdomains")
	for i := 0; i < len(iflist); i++ {
		item := newSubDomains.GetIndex(i)
		if 0 == len(item.Get("ips").MustString()) {
			continue
		}
		strHostName, err := item.Get("hostname").String()
		if nil != err {
			log.Warn("found no hostname in %v", item)
			continue
		}
		new.Set("subdomain", strHostName)
		new.Set("end", time.Now().Unix())
		bytesNew, err := new.MarshalJSON()
		if nil != err {
			log.Error("failed to marshal %v, cuz %s", new, err.Error())
			return nil
		}
		for _, handle := range conf.MQConfigInstance().NextHandlers {
			pub.PublishMessage(handle, bytesNew)
		}
	}

	return nil
}
